// pages/repairdetail/repairdetail.js
var utils = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    repairRecordId:'',
    userInfo: null,
    url: '',
    detail: null,
    accessoryDescribe: '',
    repairRecordRemark: '',
    faultDescribe: '',
    assistName:'',
    assistPhone:'',
    repairStatus:'',
    showSuccess:false,
    errorCode:'',
    testProcessDescribe:'',
    faultPhoto: [],
    // testProcessPhoto:[],
    oldImage: [],
    files: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      url: getApp().globalData.url,
      userInfo: getApp().globalData.yukaiUser
    });
    this.getDetail(options.repairRecordId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
   /**
   * 获取维修详情
   */
  getDetail: function (repairRecordId){
    wx.showLoading({
      title: '加载中',
    });
    var userInfo = this.data.userInfo ? this.data.userInfo : getApp().getUser();
    var url = this.data.url ? this.data.url : getApp().getUrl();
    var _self = this;
    wx.request({
      url: url + '/repairRecord/findByRepairId',
      data: {
        token: userInfo.token,
        repairRecordId: repairRecordId
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:   
            _self.setData({
              detail: _self.convert(data.obj),
              accessoryDescribe: data.obj.accessoryDescribe,
              repairRecordRemark: data.obj.repairRecordRemark,
              faultDescribe: data.obj.faultDescribe,
              errorCode: data.obj.errorCode && data.obj.errorCode != 'null' ? data.obj.errorCode:'',
              assistName: data.obj.assistName,
              assistPhone: data.obj.assistPhone,
              testProcessDescribe: data.obj.testProcessDescribe
            });
            wx.hideLoading();
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  convert: function(obj){
    var faultPhoto;
    var testProcessPhoto ;
    if (obj.faultPhoto){
      faultPhoto = obj.faultPhoto.split('-');
      faultPhoto.pop();
    }else{
      faultPhoto = [];
    }
    if (obj.testProcessPhoto) {
      testProcessPhoto = obj.testProcessPhoto.split('-');
      testProcessPhoto.pop();
    } else {
      testProcessPhoto = [];
    }
    this.setData({
      faultPhoto: faultPhoto,
      oldImage: testProcessPhoto
    });
    return  {
      equipmentName: obj.equipmentName,
      equipmentSerial: obj.equipmentSerial,
      eqiupmentModel: obj.eqiupmentModel,
      hospitalName: obj.hospitalName,
      departmentName: obj.departmentName,
      staffName: obj.staffName,
      applyDate: utils.formatTime(new Date(obj.applyDate)),
      repairDate: obj.repairDate ? utils.formatTime(new Date(obj.repairDate)):null,
      hospitalName: obj.hospitalName,
      acceptanceStatus: obj.acceptanceStatus,
      repairStatus: obj.repairStatus,
      repairRecordId: obj.repairRecordId,
      assistName: obj.assistName,
      assistPhone: obj.assistPhone,
      errorCode: obj.errorCode
    };
  },
   //上传图片
  chooseImage: function (e) {
    var that = this;
    var userInfo = this.data.userInfo;
    wx.chooseImage({
      count: 5,//一次最多上传5张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var files = that.data.files;
        for (var i = 0; i < tempFilePaths.length; i++) {
          //启动上传等待中...  
          wx.showLoading({
            title: '上传中'
          });
          wx.uploadFile({
            url: that.data.url + '/repairRecord/uploadRepairPhoto',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              token: userInfo.token
            },
            success: function (res) {
              console.log(res);
              var data = JSON.parse(res.data);
              //do something
              wx.hideLoading();
              var src = data.obj.split('-')[0];
              files.push(that.data.url + '/resource/images/repair_remark/' + src);
              that.setData({
                files: files
              });
            },
            fail: function () {
              utils.alertBox('图片上传失败，请重试');
            }
          })
        }
      }
    })
  },
  //预览图片
  previewFaultImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.faultPhoto // 需要预览的图片http链接列表
    })
  },
  //预览图片
  previewOldImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.oldImage // 需要预览的图片http链接列表
    })
  },
  //预览图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  //删除照片
  deleteImage: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除照片',
      success: function (res) {
        if (res.confirm) {
          var files = that.data.files;
          files.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            files: files
          });
        }
      }
    })
  },
  //actionsheet
  open: function (itemList) {
    var _self = this;
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        if (!res.cancel) {
          switch (itemList[res.tapIndex]){
            case '维修完成':
              _self.onConfirm(_self.data.detail.repairStatus);
              break;
            case '无法修复':
              _self.repairResult(4);
              break;
            case '请求技术中心支持': 
              _self.repairResult(3);
            break;
            case '返厂维修':
              _self.repairResult(2);
            break;
            case '推送紧急维修':
            _self.send();
            break;
            default:break;
          }
        }
      }
    });
  },
  onConfirm: function (repairStatus) {
    if (repairStatus==1){
      if (!utils.reg.isNull(this.data.errorCode) || !utils.reg.isNull(this.data.accessoryDescribe) || !utils.reg.isNull(this.data.repairRecordRemark) || !utils.reg.isNull(this.data.faultDescribe) || !utils.reg.isNull(this.data.testProcessDescribe)) {
        utils.alertBox('请将信息填写完整');
      } else {
        this.repairResult(repairStatus);
      }
    } else if (repairStatus == 2 || repairStatus==3){
      if (!utils.reg.isNull(this.data.errorCode) || !utils.reg.isNull(this.data.assistName) || !utils.reg.isNull(this.data.assistPhone) || !utils.reg.isNull(this.data.accessoryDescribe) || !utils.reg.isNull(this.data.repairRecordRemark) || !utils.reg.isNull(this.data.faultDescribe) || !utils.reg.isNull(this.data.testProcessDescribe)) {
        utils.alertBox('请将信息填写完整');
      } else {
        if (!utils.reg.isPhone(this.data.assistPhone)) {
          utils.alertBox('请填写正确的手机号码');
        } else {
          this.repairResult(repairStatus);
        }
      }
    }  
  },
  openSheet1: function(e){
    getApp().globalData.formId.push(e.detail.formId);
    var itemList = ['维修完成', '请求技术中心支持', '返厂维修','无法修复','推送紧急维修'];
    this.open(itemList);
  },
  openSheet2: function (e) {
    getApp().globalData.formId.push(e.detail.formId);
    var itemList = ['维修完成', '无法修复', '推送紧急维修'];
    this.open(itemList);
  },
  /**
  * bindInput
  */
  inputFault: function (e) {
    this.setData({
      faultDescribe: e.detail.value
    });
  },
  inputRemark: function (e) {
    this.setData({
      repairRecordRemark: e.detail.value
    });
  },
  inputAccessory: function (e) {
    this.setData({
      accessoryDescribe: e.detail.value
    });
  },
  inputCode: function(e){
    this.setData({
      errorCode: e.detail.value
    });
  },
  employeeName: function (e) {
    this.setData({
      assistName: e.detail.value
    });
  },
  employeePhone: function (e) {
    this.setData({
      assistPhone: e.detail.value
    });
  },
  inputTestProcess: function (e) {
    this.setData({
      testProcessDescribe: e.detail.value
    });
  },
  /**
  * 
  */
  //保存信息
  save: function(){
    wx.showLoading({
      mask:true
    });
    var userInfo = this.data.userInfo;
    var url = this.data.url;
    var _self = this;
    var data = {
      token: userInfo.token,
      repairRecordId: this.data.detail.repairRecordId,
      faultDescribe: this.data.faultDescribe,
      repairRecordRemark: this.data.repairRecordRemark,
      accessoryDescribe: this.data.accessoryDescribe,
      testProcessPhoto: this.joinPhoto(),
      errorCode: this.data.errorCode,
      assistName: this.data.assistName,
      assistPhone: this.data.assistPhone,
      testProcessDescribe: this.data.testProcessDescribe
    };
    wx.request({
      url: url + '/repairRecord/edit',
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            wx.hideLoading();
            var oldImage = _self.data.oldImage;
            for (let i = 0; i < _self.data.files.length;i++){
              oldImage.push(_self.data.files[i]);
            }
            _self.setData({
              oldImage: oldImage,
              files:[]
            });
            utils.alertBox('保存成功');
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:1
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  joinPhoto: function () {
    var photo = '';
    var files = this.data.files;
    for (var i = 0; i < files.length; i++) {
      photo += files[i] + '-';
    }
    return photo;
  },
  //维修结果
  repairResult: function (repairStatus){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否提交维修结果？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            mask: true
          });
          var userInfo = _self.data.userInfo;
          var url = _self.data.url;
          wx.request({
            url: url + '/repairRecord/fillRepairResult',
            data: {
              token: userInfo.token,
              staffId: userInfo.staffId,
              repairRecordId: _self.data.detail.repairRecordId,
              repairStatus: repairStatus,
              assistName: _self.data.assistName,
              assistPhone: _self.data.assistPhone,
              errorCode: _self.data.errorCode,
              accessoryDescribe: _self.data.accessoryDescribe,
              repairRecordRemark: _self.data.repairRecordRemark,
              faultDescribe: _self.data.faultDescribe,
              testProcessPhoto: _self.joinPhoto(),
              testProcessDescribe: _self.data.testProcessDescribe
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res.data);
              var data = res.data;
              switch (data.code) {
                case 200:                  
                  wx.hideLoading();
                  _self.setData({
                    showSuccess: true
                  });
                  break;
                case 412:
                  wx.hideLoading();
                  utils.alertBox(data.msg);
                  break;
                case 422:
                  wx.hideLoading();
                  utils.toLogin();
                  break;
                default:
                  wx.hideLoading();
                  break;
              }
            },
            fail: function () {
              wx.hideLoading();
              utils.alertBox('请求失败，请检查网络');
            }
          });
        }
      }
    })
  },
  //推送
  send: function(){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否推送紧急维修？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            mask: true
          });
          var userInfo = _self.data.userInfo;
          var url = _self.data.url;
          wx.request({
            url: url + '/repairRecord/send',
            data: {
              token: userInfo.token,
              staffId: userInfo.staffId,
              repairRecordId: _self.data.detail.repairRecordId,
              assistName: _self.data.assistName,
              assistPhone: _self.data.assistPhone,
              errorCode: _self.data.errorCode,
              accessoryDescribe: _self.data.accessoryDescribe,
              repairRecordRemark: _self.data.repairRecordRemark,
              faultDescribe: _self.data.faultDescribe,
              testProcessPhoto: _self.joinPhoto(),
              testProcessDescribe: _self.data.testProcessDescribe,
              formId: getApp().globalData.formId[0]
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res.data);
              var data = res.data;
              switch (data.code) {
                case 200:
                  _self.setData({
                    showSuccess: true
                  });
                  getApp().globalData.formId = [];
                  wx.hideLoading();
                  break;
                case 412:
                  wx.hideLoading();
                  utils.alertBox(data.msg);
                  break;
                case 422:
                  wx.hideLoading();
                  utils.toLogin();
                  break;
                default:
                  wx.hideLoading();
                  break;
              }
            },
            fail: function () {
              wx.hideLoading();
              utils.alertBox('请求失败，请检查网络');
            }
          });
        }
      }
    })
  },
  //确认维修完成
  completed:function(){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '确认维修完成？',
      success: function (res) {
        if (res.confirm) {
          _self.accept(2);
        }
      }
    })
  },
  //维修未完成，退回
  uncompleted:function(){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否退回申请？',
      success: function (res) {
        if (res.confirm) {
          _self.accept(1);
        }
      }
    })
  },
  accept: function (isComplete){
    wx.showLoading({});
    var _self = this;
    var userInfo = this.data.userInfo;
    var url = this.data.url;
    wx.request({
      url: url + '/repairRecord/acceptanceComfirm',
      data: {
        token:userInfo.token,
        repairRecordId: _self.data.detail.repairRecordId,
        staffId:userInfo.staffId,
        isComplete:isComplete
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            wx.hideLoading();
            _self.setData({
              showSuccess: true
            });
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  //同意报废
  discarded: function(){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '确认维修结果？',
      success: function (res) {
        if (res.confirm) {
          _self.discard(2);
        }
      }
    })
  },
  //不同意报废
  notDiscarded: function(){
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否退回申请？',
      success: function (res) {
        if (res.confirm) {
          _self.discard(1);
        }
      }
    })
  },
  //报废处理
  discard: function (isScrap){
    wx.showLoading({});
    var _self = this;
    var userInfo = this.data.userInfo;
    var url = this.data.url;
    wx.request({
      url: url + '/repairRecord/scrapComfirm',
      data: {
        token: userInfo.token,
        repairRecordId: _self.data.detail.repairRecordId,
        staffId: userInfo.staffId,
        isScrap: isScrap
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            wx.hideLoading();
            _self.setData({
              showSuccess: true
            });
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  }
})